#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
FTPFileName='/opt/coopgis/fromgps/anonymousftproot_OtherReadOnly/incomingftpallpermissions/Locations.csv'
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopgis/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
import djangoproject
from djangoproject.models import *
#********************Setup psycopg2 and django section********************
import COOPGIS_Ajax, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update
from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings

def BuildManagementConsoleForm():
    Dict={}
    Dict['ReprocessCommandsIndicator']=forms.BooleanField(required=False)
    Dict['DeleteCommandsIndicator']=forms.BooleanField(required=False)
    Dict['TurnDebugOnIndicator']=forms.BooleanField(required=False)
    Dict['TurnDebugOffIndicator']=forms.BooleanField(required=False)
    Dict['RestartIndicator']=forms.BooleanField(required=False)
    Dict['RebootIndicator']=forms.BooleanField(required=False)
    Dict['UpdateCleanupIndicator']=forms.BooleanField(required=False)
    Dict['RebuildSymbologyIndicator']=forms.BooleanField(required=False)
    return Dict



def ProcessManagementConsoleForm(form, request, ApplicationName):
    from django import db
    try:
        ReprocessCommandsIndicator=bool(form.data['ReprocessCommandsIndicator'] == 'on')
    except:
        ReprocessCommandsIndicator=False
    try:
        DeleteCommandsIndicator=bool(form.data['DeleteCommandsIndicator'] == 'on')
    except:
        DeleteCommandsIndicator=False
    try:
        TurnDebugOnIndicator=bool(form.data['TurnDebugOnIndicator'] == 'on')
    except:
        TurnDebugOnIndicator=False
    try:
        TurnDebugOffIndicator=bool(form.data['TurnDebugOffIndicator'] == 'on')
    except:
        TurnDebugOffIndicator=False
    try:
        RestartIndicator=bool(form.data['RestartIndicator'] == 'on')
    except:
        RestartIndicator=False
    try:
        RebootIndicator=bool(form.data['RebootIndicator'] == 'on')
    except:
        RebootIndicator=False
    try:
        UpdateCleanupIndicator=bool(form.data['UpdateCleanupIndicator'] == 'on')
    except:
        UpdateCleanupIndicator=False
    try:
        TurnServerOnIndicator=bool(form.data['TurnServerOnIndicator'] == 'on')
    except:
        TurnServerOnIndicator=False
    try:
        TurnServerOffIndicator=bool(form.data['TurnServerOffIndicator'] == 'on')
    except:
        TurnServerOffIndicator=False
    try:
        RebuildSymbologyIndicator=bool(form.data['RebuildSymbologyIndicator'] == 'on')
    except:
        RebuildSymbologyIndicator=False

    Results=[]


    if(TurnDebugOnIndicator):
        Results.append('Turning Debug On, the server may need to be restarted')
        os.system("sudo -u apachescript sudo sed -i 's/DEBUG=False/DEBUG=True/' /opt/coopgis/djangoproject/settings.py")
    if(TurnDebugOffIndicator):
        Results.append('Turning Debug Off, the server may need to be restarted')
        os.system("sudo -u apachescript sudo sed -i 's/DEBUG=True/DEBUG=False/' /opt/coopgis/djangoproject/settings.py")
    if(RestartIndicator and not djangoproject.settings.COOPGISServerIndicator):
        Results.append('Restarting Apache Server') #User should actually get an error message
        os.system("sudo -u apachescript sudo /etc/init.d/apache2 force-reload")


    LoginStatus, applicationPermission=COOPGIS_Misc.CheckLoginPermissions(request, ApplicationName + 'Admin')

    if(applicationPermission and ReprocessCommandsIndicator):
        Results.append('Reprocessed commands that failed to process')
        command.Reprocess()
    if(applicationPermission and DeleteCommandsIndicator):
        Results.append('Deleted commands that failed to process and were not processed')
        Command.objects.filter(CommandProcessFailedIndicator=True).exclude(CommandProcessedIndicator=True).delete()
    if(applicationPermission and UpdateCleanupIndicator):
        try:
            os.remove('/opt/coopgis/DataNotPartOfCOOPGIS/DatabaseDumpInProgress.txt')
            Results.append('deleted /opt/coopgis/DataNotPartOfCOOPGIS/DatabaseDumpInProgress.txt')
        except:
            Results.append('Failed to delete /opt/coopgis/DataNotPartOfCOOPGIS/DatabaseDumpInProgress.txt')
        FileList=os.listdir(djangoproject.settings.COOPGISUpdatePathInProgress)
        os.system('sudo -u apachescript sudo mkdir ' + djangoproject.settings.COOPGISUpdatePathCancelled)
        os.system('sudo -u apachscript sudo chmod -R 777 ' + djangoproject.settings.COOPGISUpdatePathCancelled)
        for i in FileList:
            shutil.move(djangoproject.settings.COOPGISUpdatePathInProgress + i, djangoproject.settings.COOPGISUpdatePathCancelled + i)
            Results.append('Moved In Progress File Out of the way:  ' + str(i))
    if(applicationPermission and RebootIndicator):
        Results.append('Rebooting the Server') #User should actually get an error message [or their computer should reboot if local]
        os.system("sudo -u apachescript sudo sync")
        time.sleep(1)
        os.system("sudo -u apachescript sudo reboot")
    if(applicationPermission and RebuildSymbologyIndicator):
        Results.append('Rebuilding Symbology')
        StationIds = djangoproject.models.geography.Station.objects.all().values_list('id', flat=True)
        for stationid in StationIds:
            Station=djangoproject.models.geography.Station.objects.filter(id=stationid)
            if(Station):
                Station[0].RebuildSymbology()
            db.reset_queries()
    return '\n'.join(Results)


